package com.jumi.microservice.service.logistics.express;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jumi.microservice.common.file.Md5Utils;
import com.jumi.microservice.common.utils.HttpClientUtils;
import com.jumi.microservice.dto.logistics.Logistics;
import com.jumi.microservice.dto.logistics.LogisticsSearchRequest;
import com.jumi.microservice.dto.logistics.LogisticsSearchResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by mazhao
 * 百世快递
 * @Classname BestExpress
 * @Description TODO
 * @Date 2020/8/21 14:30
 */
@Service
public class BestExpress extends ResponseController implements Express {

    private static final Logger log = LoggerFactory.getLogger(BestExpress.class);

    @Resource
    HttpClientUtils httpClientUtils;

    private static String url = "http://edi-q9.ns.800best.com/kd/api/process";
    private static String partnerKey ="evuoq7qj8zpd";
    private static String partnerID = "66043";
    private static String serviceType="KD_TRACE_QUERY";

    @Override
    public String expressCode() {
        return "HTKY";
    }

    @Override
    public LogisticsSearchResponse logisticsSearch(LogisticsSearchRequest request) {
        log.info("百世快递查询参数[{}]", JSON.toJSONString(request));
        JSONArray jsonArr = null;
        LogisticsSearchResponse logisticsSearchResponse = null;
        try {
            //拼接请求头
            Map<String,String> headers = new HashMap<>(4);
            headers.put("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            headers.put("connection", "keep-alive");
            headers.put("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
            headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            //组建数据格式
            String bizData = "{\"mailNos\": {\"mailNo\": [\""+request.getLogisticsNo()+"\"]}}";
            String sign = Md5Utils.hash(bizData+partnerKey);
            String requestData ="partnerID="+partnerID+"&serviceType="+serviceType+"&bizData="+bizData+"&sign="+sign;
            //发送请求并接受返回
            String res = httpClientUtils.post(url, requestData, headers);
            log.info("请求返回结果[{}]",res);
            JSONObject json = JSONObject.parseObject(res);
            jsonArr = json.getJSONArray("traceLogs");
            //处理返回结果
            jsonArr = jsonArr.getJSONObject(0).getJSONObject("traces").getJSONArray("trace");
        } catch (Exception e) {
            log.error("百世快递查询出错[{}]",e.getMessage());
        }
        logisticsSearchResponse = checkResult(jsonArr,request);
        return controller(logisticsSearchResponse,jsonArr,"remark","acceptTime");
    }

}
